package org.budo.graph.metric;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/**
 * @author lmw
 */
@Getter
@Setter
@NoArgsConstructor
@ToString
public class Metric implements Serializable {
    private static final long serialVersionUID = 3482609565721683157L;

    // 统计目标
    private String key;

    // 是否记录统计曲线
    private Boolean graph;

    // 截止目前 执行次数
    private AtomicLong executeCount = new AtomicLong(0);

    // 累计的总的执行耗时
    private AtomicLong executeTimeNanos = new AtomicLong(0);

    // 存储正在执行的请求，和他的开始时间
    private Map<String, Long> running = new ConcurrentHashMap<String, Long>();

    public Metric(String key, Boolean graph) {
        this.key = key;
        this.graph = graph;
    }

    // 增加一条正在执行的
    public void before(String uuid) {
        running.put(uuid, System.nanoTime());
    }

    // 结束一条正在执行的
    public void after(String uuid) {
        Long startAt = running.get(uuid); // 开始时间
        Long executeTime = System.nanoTime() - startAt; // 执行耗时

        executeCount.addAndGet(1L); // 次数+1
        executeTimeNanos.addAndGet(executeTime); // 耗时累加
        running.remove(uuid);
    }
}